package com.example.rabbitboot.sender;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * @author lzh
 * @date 2019/9/18 - 16:03
 */
@Component
@Slf4j
public class DefaultRabbitSender implements RabbitTemplate.ConfirmCallback ,RabbitTemplate.ReturnCallback{

    @Autowired
    private RabbitTemplate rabbitTemplate;


    public void sendMsg(String exchange , String routingKey ,String content) {
        CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
        //rabbitTemplate如果为单例的话，那回调就是最后设置的内容
        this.rabbitTemplate.setConfirmCallback(this::confirm);
        this.rabbitTemplate.setReturnCallback(this::returnedMessage);
        this.rabbitTemplate.convertAndSend(exchange,  routingKey, content, correlationId);
    }


    /**
     * 使用场景：
     *
     * 如果消息没有到exchange,则confirm回调,ack=false
     *
     * 如果消息到达exchange,则confirm回调,ack=true
     *
     * exchange到queue成功,则不回调return
     *
     * exchange到queue失败,则回调return(需设置mandatory=true,否则不回回调,消息就丢了)
     */



    /**
     * 回调 生产者不确认 下面程序不会执行
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if(ack){
            log.info("消费发送成功!!!消息id为: "+correlationData+"的消息，已经被ack成功");
        }else{
            log.info("消费发送失败!!!!消息id为: "+correlationData+"的消息，消息nack，失败原因是："+cause);
        }
    }


    /**
     * 没有exchange,消息回退 下面程序会执行
     */
    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        log.info("收到回调");
        log.info("return--message:" + new String(message.getBody()) + ",replyCode:" + replyCode + ",replyText:" + replyText + ",exchange:" + exchange + ",routingKey:" + routingKey);
    }



}
